package com.gogowan.agroenterprise.contorl;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.gogowan.agroenterprise.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;

public class HttpConnectService {
    private static final int NOTIFY_ID = 0;
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private TextView textview = null;
    private ProgressBar bar = null;
    private UrlErrorLestener urlErrorLestener=null;
    public HttpConnectService(TextView textview, ProgressBar bar) {
        this.textview = textview;
        this.bar = bar;
    }
    // 下载地址

    // 下载包安装路径
    private static String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/cxx.apk";

    public static String getDiskCacheDir(Context context, String uniqueName) {
        final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState()) ? getExternalCacheDir(context)
                .getPath() : context.getCacheDir().getPath();
//        return cachePath + File.separator + uniqueName;
        return Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+uniqueName;
    }

    //    final String cacheDir = "/Android/data/" + context.getPackageName()
//            + "/cache/";
    public static File getExternalCacheDir(Context context) {
        final String cacheDir = "/Android/data/";
        return new File(Environment.getExternalStorageDirectory().getPath()
                + cacheDir);
    }

    public void connectDownLoad(final Context context, final String packageName, final String apkUrl) {
        savePath = getDiskCacheDir(context, "UpApp.Apk");
        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        HttpUtils http = new HttpUtils();
        http.configTimeout(30000);
        http.configSoTimeout(30000);
        http.download(apkUrl, savePath, false, false,
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        setUpNotification(packageName, context);
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        int progress = (int) (current * 100 / total);
                        textview.setText("正在更新 (" + progress + "%)");
                        bar.setProgress(progress);
                        RemoteViews contentview = mNotification.contentView;
                        contentview.setTextViewText(R.id.tv_progress, progress + "%");
                        contentview.setProgressBar(R.id.progressbar, 100, progress, false);
                        mNotificationManager.notify(NOTIFY_ID, mNotification);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        mNotificationManager.cancel(NOTIFY_ID);
                        installAPK(responseInfo.result, context);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        urlErrorLestener.ErrorMessage(error,msg);
                        RemoteViews contentview = mNotification.contentView;
                        textview.setText("下载失败");
                        bar.setVisibility(View.GONE);
                        contentview.setTextViewText(R.id.tv_progress, "下载失败");
                        contentview.setProgressBar(R.id.progressbar, 100, 0, false);
                        mNotificationManager.notify(NOTIFY_ID, mNotification);
                    }
                });

    }
    public interface UrlErrorLestener{
        void ErrorMessage(HttpException errorException, String msg);
    }
    public void setOnErrorLestener(UrlErrorLestener errorLestener){
        urlErrorLestener=errorLestener;
    }
    /**
     * 创建通知
     */
    @SuppressWarnings("deprecation")
    private void setUpNotification(String packageName, Context context) {
        mNotification = new Notification(R.drawable.logo, "正在下载", System.currentTimeMillis());
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        RemoteViews contentView = new RemoteViews(packageName, R.layout.download_notification_layout);
        mNotification.contentView = contentView;
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    //安装APK
    private void installAPK(File file, Context context) {
        Intent intent =new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Uri uri = Uri.fromFile(apkFile);
        Uri uri = null;
        //todo N FileProvider
        //todo O install permission
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            uri = FileProvider.getUriForFile(context, "downxml", file);
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }else{
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);


    }

}
